<script>
import { checkLogin } from './libs/login';
import { HTTP_REQUEST_URL, SYSTEM_VERSION } from './config/app';
import { getShopConfig, silenceAuth, getSystemVersion, basicConfig, remoteRegister } from '@/api/public';
import Auth from '@/libs/wechat.js';
import Routine from './libs/routine.js';
import { silenceBindingSpread } from '@/utils';
import { colorChange, getCrmebCopyRight } from '@/api/api.js';
import { getLangJson, getLangVersion } from '@/api/user.js';
import { mapGetters } from 'vuex';
import colors from '@/mixins/color.js';
import Cache from '@/utils/cache';
import themeList from '@/utils/theme';

export default {
	globalData: {
		spid: 0,
		code: 0,
		isLogin: false,
		userInfo: {},
		MyMenus: [],
		globalData: false,
		isIframe: false,
		tabbarShow: true,
		windowHeight: 0,
		locale: '',
		HTTP_REQUEST_URL: HTTP_REQUEST_URL,
		extraData: null
	},
	mixins: [colors],
	computed: mapGetters(['isLogin']),
	onShow() {
		const queryData = uni.getEnterOptionsSync(); // uni-app版本 3.5.1+ 支持
		
		// 接收微信小程序跳转参数
		if (queryData.referrerInfo && queryData.referrerInfo.extraData) {
			console.log('App onShow: 检测到小程序跳转参数', JSON.stringify(queryData.referrerInfo.extraData));
			const extraData = queryData.referrerInfo.extraData;
			
			// 保存跳转参数到globalData
			this.globalData.extraData = extraData;
			
			// 保存用户信息到本地存储
			if (extraData.token) {
				uni.setStorageSync('token', extraData.token);
				// 设置登录状态
				this.$store.commit('LOGIN', {
					token: extraData.token,
					time: 7200 // 默认2小时过期时间
				});
				console.log('App onShow: 已保存token并设置登录状态');
			}
			
			if (extraData.avatar) {
				uni.setStorageSync('avatar', extraData.avatar);
				console.log('App onShow: 已保存avatar');
			}
			
			if (extraData.nickname) {
				uni.setStorageSync('nickname', extraData.nickname);
				console.log('App onShow: 已保存nickname');
			}
			
			if (extraData.userId) {
				uni.setStorageSync('userId', extraData.userId);
				this.$store.commit('SETUID', extraData.userId);
				console.log('App onShow: 已保存userId');
			}
		}
		
		if (queryData.query.spread) {
			this.$Cache.set('spread', queryData.query.spread);
			this.globalData.spid = queryData.query.spread;
			this.globalData.pid = queryData.query.spread;
			silenceBindingSpread(this.globalData);
		}
		if (queryData.query.spid) {
			this.$Cache.set('spread', queryData.query.spid);
			this.globalData.spid = queryData.query.spid;
			this.globalData.pid = queryData.query.spid;
			silenceBindingSpread(this.globalData);
		}
		// #ifdef MP
		if (queryData.query.scene) {
			let param = this.$util.getUrlParams(decodeURIComponent(queryData.query.scene));
			if (param.pid) {
				this.$Cache.set('spread', param.pid);
				this.globalData.spid = param.pid;
				this.globalData.pid = param.pid;
			} else {
				switch (queryData.scene) {
					//扫描小程序码
					case 1047:
						this.globalData.code = queryData.query.scene;
						break;
					//长按图片识别小程序码
					case 1048:
						this.globalData.code = queryData.query.scene;
						break;
					//手机相册选取小程序码
					case 1049:
						this.globalData.code = queryData.query.scene;
						break;
					//直接进入小程序
					case 1001:
						this.globalData.spid = queryData.query.scene;
						break;
				}
			}
			silenceBindingSpread(this.globalData);
		}
		// #endif
	},
	async onLaunch(option) {
		let that = this;
		
		// 接收微信小程序跳转参数
		if (option.referrerInfo && option.referrerInfo.extraData) {
			console.log('App onLaunch: 检测到小程序跳转参数', JSON.stringify(option.referrerInfo.extraData));
			const extraData = option.referrerInfo.extraData;
			
			// 保存跳转参数到globalData
			this.globalData.extraData = extraData;
			
			// 保存用户信息到本地存储
			if (extraData.token) {
				uni.setStorageSync('token', extraData.token);
				// 设置登录状态
				this.$store.commit('LOGIN', {
					token: extraData.token,
					time: 7200 // 默认2小时过期时间
				});
				console.log('App onLaunch: 已保存token并设置登录状态');
			}
			
			if (extraData.avatar) {
				uni.setStorageSync('avatar', extraData.avatar);
				console.log('App onLaunch: 已保存avatar');
			}
			
			if (extraData.nickname) {
				uni.setStorageSync('nickname', extraData.nickname);
				console.log('App onLaunch: 已保存nickname');
			}
			
			if (extraData.userId) {
				uni.setStorageSync('userId', extraData.userId);
				this.$store.commit('SETUID', extraData.userId);
				console.log('App onLaunch: 已保存userId');
			}
		}
		
		basicConfig().then((res) => {
			uni.setStorageSync('BASIC_CONFIG', res.data);
		});
		// #ifdef H5
		if (option.query.hasOwnProperty('mdType') && option.query.mdType == 'iframeWindow') {
			this.globalData.isIframe = true;
		} else {
			this.globalData.isIframe = false;
		}
		if (!this.isLogin && option.query.hasOwnProperty('remote_token')) {
			this.remoteRegister(option.query.remote_token);
		}
		// #endif
		colorChange('color_change').then((res) => {
			const themeMap = {
				1: 'blue',
				2: 'green',
				3: 'red',
				4: 'pink',
				5: 'orange'
			};
			uni.setStorageSync('is_diy', res.data.is_diy);
			uni.$emit('is_diy', res.data.is_diy);
			const status = res.data.status;
			const themeKey = themeMap[status] || 'red'; // 默认使用红色
			const selectedTheme = themeList[themeKey];
			uni.setStorageSync('color_status', res.data.status);
			uni.setStorageSync('viewColor', selectedTheme);
			uni.$emit('ok', selectedTheme, status);
		});
		getLangVersion().then((res) => {
			let version = res.data.version;
			if (version != uni.getStorageSync('LANG_VERSION')) {
				getLangJson().then((res) => {
					let value = Object.keys(res.data)[0];
					Cache.set('locale', Object.keys(res.data)[0]);
					this.$i18n.setLocaleMessage(value, res.data[value]);
					uni.setStorageSync('localeJson', res.data);
				});
			}
			uni.setStorageSync('LANG_VERSION', version);
		});

		// #ifdef APP-PLUS || H5
		uni.getSystemInfo({
			success: function (res) {
				// 首页没有title获取的整个页面的高度，里面的页面有原生标题要减掉就是视口的高度
				// 状态栏是动态的可以拿到 标题栏是固定写死的是44px
				let height = res.windowHeight - res.statusBarHeight - 44;
				// #ifdef H5 || APP-PLUS
				that.globalData.windowHeight = res.windowHeight + 'px';
				// #endif
			}
		});
		// #endif
		// #ifdef MP
		if (HTTP_REQUEST_URL == '') {
			console.error(
				"请配置根目录下的config.js文件中的 'HTTP_REQUEST_URL'\n\n请修改开发者工具中【详情】->【AppID】改为自己的Appid\n\n请前往后台【小程序】->【小程序配置】填写自己的 appId and AppSecret"
			);
			return false;
		}

		const updateManager = wx.getUpdateManager();
		const startParamObj = wx.getEnterOptionsSync();
		if (wx.canIUse('getUpdateManager') && startParamObj.scene != 1154) {
			const updateManager = wx.getUpdateManager();
			updateManager.onCheckForUpdate(function (res) {
				// 请求完新版本信息的回调
				if (res.hasUpdate) {
					updateManager.onUpdateFailed(function () {
						return that.Tips({
							title: '新版本下载失败'
						});
					});
					updateManager.onUpdateReady(function () {
						wx.showModal({
							title: '更新提示',
							content: '新版本已经下载好，是否重启当前应用？',
							success(res) {
								if (res.confirm) {
									updateManager.applyUpdate();
								}
							}
						});
					});
					updateManager.onUpdateFailed(function () {
						wx.showModal({
							title: '发现新版本',
							content: '请删除当前小程序，重启搜索打开...'
						});
					});
				}
			});
		}
		// #endif

		// 获取导航高度；
		uni.getSystemInfo({
			success: function (res) {
				that.globalData.navHeight = res.statusBarHeight * (750 / res.windowWidth) + 91;
			}
		});
		// #ifdef MP
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		that.globalData.navH = menuButtonInfo.top * 2 + menuButtonInfo.height / 2;
		const version = uni.getSystemInfoSync().SDKVersion;
		if (Routine.compareVersion(version, '2.21.3') >= 0) {
			that.$Cache.set('MP_VERSION_ISNEW', true);
		} else {
			that.$Cache.set('MP_VERSION_ISNEW', false);
		}
		// #endif

		// #ifdef H5
		// 添加crmeb chat 统计
		var __s = document.createElement('script');
		__s.src = `${HTTP_REQUEST_URL}/api/get_script`;
		document.head.appendChild(__s);
		// #endif
		getCrmebCopyRight().then((res) => {
			uni.setStorageSync('copyRight', res.data);
		});
	},
	// #ifdef H5
	onHide() {
		this.$Cache.clear('snsapiKey');
	},
	// #endif
	methods: {
		remoteRegister(remote_token) {
			remoteRegister({ remote_token }).then((res) => {
				let data = res.data;
				if (data.get_remote_login_url) {
					location.href = data.get_remote_login_url;
				} else {
					this.$store.commit('LOGIN', {
						token: data.token,
						time: data.expires_time - this.$Cache.time()
					});
					this.$store.commit('SETUID', data.userInfo.uid);
					location.reload();
				}
			});
		}
	}
};
</script>

<style lang="scss">
/*每个页面公共css */
page {
	min-height: 100vh;
	box-sizing: border-box;
	background-color: #f5f5f5;
	padding-bottom: env(safe-area-inset-bottom); /* 适配全面屏底部安全区域 */
}

/* tabBar 样式 */
.uni-tabbar {
	border-top: 1px solid rgba(0, 0, 0, 0.1);
	box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
	background-color: #fff;
}

.uni-tabbar-bottom {
	bottom: 0;
	padding-bottom: env(safe-area-inset-bottom);
}

.uni-tabbar__item {
	height: 50px;
	padding: 5px 0;
}

.uni-tabbar__icon {
	width: 24px;
	height: 24px;
}

.uni-tabbar__label {
	font-size: 10px;
	line-height: 12px;
	margin-top: 3px;
}

/* 修复底部导航栏遮挡内容问题 */
.content-wrapper {
	padding-bottom: calc(50px + env(safe-area-inset-bottom));
}
</style>
